package com.zb.zeus.common.engine.domain;

import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

/**
 * 时间区间单位
 * @author fujianjian
 * @since 2021/5/21 10:58
 */
@Getter
public enum DurUnit {
    /**
     *
     */
    YEAR("year", "年") {
        @Override
        public long getDuration(long start, long end) {
            return ChronoUnit.YEARS.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(end), ZoneId.systemDefault()));
        }
    },
    MONTH("month", "月"){
        @Override
        public long getDuration(long start, long end) {
            return ChronoUnit.MONTHS.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(end), ZoneId.systemDefault()));
        }
    },
    DAY("day", "日"){
        @Override
        public long getDuration(long start, long end) {
            return ChronoUnit.DAYS.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(end), ZoneId.systemDefault()));
        }
    },
    HOUR("hour", "时"){
        @Override
        public long getDuration(long start, long end) {
            return ChronoUnit.HOURS.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(end), ZoneId.systemDefault()));
        }
    },
    MINUTE("min", "分"){
        @Override
        public long getDuration(long start, long end) {
            return ChronoUnit.MINUTES.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(end), ZoneId.systemDefault()));
        }
    },
    SECOND("sec", "秒"){
        @Override
        public long getDuration(long start, long end) {
            return ChronoUnit.SECONDS.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault()),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(end), ZoneId.systemDefault()));
        }
    },
    ;
    private String code;
    private String desc;

    DurUnit(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public abstract long getDuration(long start, long end);

    public static DurUnit getInstance(String code) {
        for (DurUnit value : DurUnit.values()) {
            if (StringUtils.equalsIgnoreCase(value.getCode(), code)) {
                return value;
            }
        }
        return DAY;
    }
}
